package edu.tongji.jiaowu.webapp.action;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.acegisecurity.Authentication;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.context.SecurityContextHolder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import com.tongji.quickCRUDQ.define.Column;
import com.tongji.quickCRUDQ.define.Row;
import com.tongji.quickCRUDQ.define.Table;
import com.tongji.quickCRUDQ.exception.FormatException;
import com.tongji.quickCRUDQ.model.CommonBean;
import com.tongji.quickCRUDQ.util.JsonDataSet;
import com.tongji.quickCRUDQ.util.RequestUtil;
import com.tongji.quickCRUDQ.util.StringUtil;

import edu.tongji.jiaowu.service.BasicDataManager;
import edu.tongji.jiaowu.service.GradeMajorManager;
import edu.tongji.jiaowu.service.OriginalScoreCourseManager;
import edu.tongji.jiaowu.service.ParameterManager;
import edu.tongji.jiaowu.service.ScoreManager;
import edu.tongji.jiaowu.service.StoreProcedureManager;
import edu.tongji.jiaowu.service.StudentManager;
import edu.tongji.jiaowu.service.VcodeManager;
import edu.tongji.jiaowu.service.VyearCollegeManager;
import edu.tongji.jiaowu.webapp.session.SessionParameter;
import edu.tongji.jiaowu.webapp.session.SessionParameterLocal;

public class ScoreController extends MultiActionController {
	private ParameterManager parameterManager;
	private VcodeManager vcodeManager;
	private VyearCollegeManager vyearCollegeManager;
	private GradeMajorManager gradeMajorManager;
    private StoreProcedureManager storeProcedureManager;
	private OriginalScoreCourseManager originalScoreCourseManager;
	private ScoreManager scoreManager;
	private BasicDataManager basicDataManager;
	private StudentManager studentManager;
	
	public ModelAndView queryStudentScore(HttpServletRequest request, HttpServletResponse response){
		try {
			String studentNo=request.getParameter("studentNo");
			if (studentNo==null||"".equals(studentNo)) {
				throw new FormatException("请传入学生学号");
			}
			SessionParameter parameter=(SessionParameter) request.getSession().getAttribute("SessionParameter");
			String account=parameter.getUserAccount();
			if (studentNo.equals(account)) {//学号与登录帐号一致,说明是学生在查询自己的成绩
				boolean arrears=studentManager.getArrears(studentNo);
				if (arrears) {//欠费
					throw new FormatException("对不起,暂不支持欠费学生查询成绩!");
				}
			}else{
				Authentication auth = SecurityContextHolder.getContext().getAuthentication();
				 GrantedAuthority[] authorities =auth.getAuthorities();
				 for (int i = 0; i < authorities.length; i++) {
					 GrantedAuthority role=authorities[i];
					 String roleName=role.getAuthority();
					 if ("student".equals(roleName)) {
						 throw new FormatException("查询出错");
					}
				}
			}
			
			Map scoreInfo=scoreManager.queryStudentScore(studentNo);
			StringBuffer json=new StringBuffer();
			json.append("{gradePoint:").append(scoreInfo.get("gradePoint")).append(",sumCredit:")//,semesters:");
			    .append(scoreInfo.get("sumCredit")).append(",sumPassedCredit:").append(scoreInfo.get("sumPassedCredit"))
			    .append(",failedCourseCount:").append(scoreInfo.get("failedCourseCount")).append(",semesters:");
			List semesters=(List) scoreInfo.get("semesters");
			json.append(JsonDataSet.listToJson(semesters));
			json.append(",scores:[");
			int s1=semesters.size();
			for (int i = 0; i < s1; i++) {
				Map semester=(Map) semesters.get(i);
				String schoolYear=(String) semester.get("SCHOOL_YEAR");
				String schoolSemester=(String) semester.get("SCHOOL_SEMESTER");
				List semesterScore=(List) scoreInfo.get(schoolYear+schoolSemester);
				json.append("{");
				json.append("results:").append(semesterScore.size()).append(",rows:");
				json.append(JsonDataSet.listToJson(semesterScore));
				json.append("");
				json.append("}");
				if (i<s1-1) {
					json.append(",");
				}
			}
			json.append("]");
			json.append("}");
			RequestUtil.write(response, json.toString());
		} catch (Exception e) {
			RequestUtil.writeJsonException(response, e);
		}
		return null;
	}
	
	public ModelAndView courseScoreStatistic(HttpServletRequest request, HttpServletResponse response){
		Map model = basicDataManager.semesterGradeMajorMap();
		return new ModelAndView("score/print/courseScoreStatistic","model",model);
	}
	public ModelAndView majorScoreStatistic(HttpServletRequest request, HttpServletResponse response){
		Map model =  basicDataManager.semesterGradeMajorMap();
		return new ModelAndView("score/print/majorScoreStatistic","model",model);
	}
	public ModelAndView semesterScore(HttpServletRequest request, HttpServletResponse response){
		Map model =  basicDataManager.semesterGradeMajorMap();
		return new ModelAndView("score/print/semesterScorePrint","model",model);
	}
//
//	private Map printCondition() {
//		CommonBean grades=vcodeManager.findCodes("GRADE");
//		String gradeJson=JsonDataSet.commonbeanToJsonArray(grades, "code", "name");
//		CommonBean semesters=vcodeManager.findCodes("SCHOOL_SEMESTER");
//		String semesterJson=JsonDataSet.commonbeanToJsonArray(semesters, "code", "name");
//		CommonBean years=vcodeManager.findCodes("SCHOOL_YEAR");
//		String yearJson=JsonDataSet.commonbeanToJsonArray(years, "code", "name");
//		CommonBean yearColleges=vyearCollegeManager.findAllVyearColleges();
//		String yearCollegeJson=JsonDataSet.commonbeanToJsonArray(yearColleges, "collegeId", "collegeName", "schoolYear");
//		CommonBean gradeMajors=gradeMajorManager.findAllGradeMajors();
//
//		  StringBuffer jsonArray=new StringBuffer("[");
//		  int s1=gradeMajors.getSize();
//		  for (int i = 0; i < s1; i++) {
//			  String value = gradeMajors.getPropertyAsString(i, "majorNo");
//			  String text=gradeMajors.getPropertyAsString(i, "majorName");
//			  String grade=gradeMajors.getPropertyAsString(i,"grade");
//			  String refid=gradeMajors.getPropertyAsString(i,"refid");
//			  jsonArray.append("['").append(value).append("','").append(text).append("','").append(grade).append("','").append(refid).append("']");
//			  if(i<s1-1){
//				  jsonArray.append(",");
//			  }
//		  }
//		  jsonArray.append("]");		
//		
//		Map model=new HashMap();
//		model.put("gradeJson", gradeJson);
//		model.put("semesterJson", semesterJson);
//		model.put("yearJson", yearJson);
//		model.put("yearCollegeJson", yearCollegeJson);
//		model.put("gradeMajorJson", jsonArray.toString());
//		return model;
//	}
	public ModelAndView semesterScorePrint(HttpServletRequest request, HttpServletResponse response){
		String grade=request.getParameter("grade");
		String gradeMajor=request.getParameter("gradeMajor");
		String schoolYear=request.getParameter("schoolYear");
		String schoolSemester=request.getParameter("schoolSemester");
		String[] params=new String[]{grade,gradeMajor,schoolYear,schoolSemester};
		int[] paramType=new int[]{1,1,1,1};
		storeProcedureManager.run("p_semester_score_print",paramType,params);
		return new ModelAndView("forward:/pdf/print.html");
	}
	
	
	public ModelAndView studentScore(HttpServletRequest request, HttpServletResponse response){
		Map model =  basicDataManager.semesterGradeMajorMap();
		return new ModelAndView("score/print/studentScore","model",model);
		
	}
	
	public ModelAndView studentScorePrint(HttpServletRequest request, HttpServletResponse response){
		String studentNo=request.getParameter("studentNo");
		String[] params=new String[]{studentNo};
		int[] paramType=new int[]{1};
		storeProcedureManager.run("p_student_score_print",paramType,params);
		String mask=request.getParameter("mask");
		if ("Y".equals(mask)) {
			scoreManager.maskScorePrint(studentNo);
		}
		
		return new ModelAndView("forward:/pdf/print.html");
	}
	
	public ModelAndView majorScorePrint(HttpServletRequest request, HttpServletResponse response){
		String grade=request.getParameter("grade");
		String majorNo=request.getParameter("majorNo");
		String[] params=new String[]{grade,majorNo};
		int[] paramType=new int[]{1,1};
		storeProcedureManager.run("p_batch_student_score_print",paramType,params);
		String mask=request.getParameter("mask");
		if ("Y".equals(mask)) {
			scoreManager.maskScorePrint(grade,majorNo);
		}
		return new ModelAndView("forward:/pdf/print.html");
	}

	public ModelAndView update(HttpServletRequest request, HttpServletResponse response) {
		CommonBean semesters=vcodeManager.findCodes("SCHOOL_SEMESTER");
		String semesterJson=JsonDataSet.commonbeanToJsonArray(semesters, "code", "name");
		CommonBean years=vcodeManager.findCodes("SCHOOL_YEAR");
		String yearJson=JsonDataSet.commonbeanToJsonArray(years, "code", "name");
		Map model=new HashMap();
		model.put("yearJson", yearJson);
		model.put("semesterJson", semesterJson);
		return new ModelAndView("score/update/updateCondition","model",model);
	}
	
	public ModelAndView input(HttpServletRequest request, HttpServletResponse response) {
		SessionParameter sessionParameter = (SessionParameter) request.getSession().getAttribute("SessionParameter");
		String account = sessionParameter.getUserAccount();// 用户帐号
		String scoreType=request.getParameter("SCORE_TYPE");//01-正常考试成绩,02-重修考试成绩,03-补考成绩,04-手工录入成绩
		String status=request.getParameter("STATUS");
		String year = request.getParameter("schoolYear");
		String flag = request.getParameter("flag");//flag:1--录入课程管理,2--教师录入选课课程成绩
		if (year == null){
			if ("01".equals(scoreType)||"04".equals(scoreType)) {//正常考试成绩或手工录入成绩
				year = sessionParameter.getCurrentSchoolYear();// 当前学年度
			} else if ("02".equals(scoreType)) {//重修成绩
				year = parameterManager.findParameterValue("RESTUDY_YEAR");//重修学年度
			}else if ("03".equals(scoreType)) {//补考成绩
				year = parameterManager.findParameterValue("REEXAMINATION_YEAR");//补考学年度
			}
		}		
		String semester = request.getParameter("schoolSemester");
		if (semester == null){
			if ("01".equals(scoreType)||"04".equals(scoreType)) {//正常考试成绩或手工录入成绩
				semester = sessionParameter.getCurrentSchoolSemester();// 当前学期
			} else if ("02".equals(scoreType)) {//重修成绩
				semester=parameterManager.findParameterValue("RESTUDY_SEMESTER");//重修学期
			} else if ("03".equals(scoreType)) {//补考成绩
				semester=parameterManager.findParameterValue("REEXAMINATION_SEMESTER");//补考学期
			}
		}	
		String url = "forward:/quick/quick.html?tableName=T_ORIGINAL_SCORE_COURSE&SCHOOL_YEAR=" + year + "&SCHOOL_SEMESTER=" + semester;
		if ("N".equals(status)) {//未确认的成绩
			url+= "&INPUTOR_ACCOUNT=" + account;
		}else if ("1".equals(flag)) {
			url+= "&tableAlias=T_ORIGINAL_SCORE_COURSE_INPUTOR";
		}
		return new ModelAndView(url);
	}

	public ModelAndView confirm(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("REFID");
		try {
			originalScoreCourseManager.confirm(id);
			StringBuffer json=new StringBuffer("{result:'success'}");
			RequestUtil.write(response, json.toString());
		} catch (Exception e) {
			RequestUtil.writeJsonException(response,e);
		}
		return null;
	}
	
	   public ModelAndView updateAndConfirm(HttpServletRequest request,HttpServletResponse response) throws Exception{
		   response.setCharacterEncoding("UTF-8");
		try {
	    	Map quickMap=(Map)request.getAttribute("quickMap");
	    	Table table=(Table)quickMap.get("table");
	    	Row   row  =(Row)  quickMap.get("row");
			List columns=row.getDistinctColumnList();
			Column c=row.findColumn("REFID", table.getTablename());
			c.setBparam("N");//将REFID设置为不是"request参数"
			
			String updtDataStr = request.getParameter("updtData");//修改的记录集
			List updtData=JsonDataSet.jsonToList(updtDataStr, columns);
			originalScoreCourseManager.updateAndConfirm(updtData, row);//批量处理
			StringBuffer json=new StringBuffer("{result:'success',success:true,idMap:{}}");
			RequestUtil.write(response, json.toString());
		} catch (Exception e) {
			RequestUtil.writeJsonException(response, e);
		}
			return null;
	 }

	   
	   public ModelAndView deleteFailElective(HttpServletRequest request,HttpServletResponse response) throws Exception{
		   scoreManager.deleteFailElective();
		   return new ModelAndView("redirect:/quick/quick.html?tableName=V_FAIL_ELECTIVE");
	   }

	public ParameterManager getParameterManager() {
		return parameterManager;
	}

	public void setParameterManager(ParameterManager parameterManager) {
		this.parameterManager = parameterManager;
	}

	public OriginalScoreCourseManager getOriginalScoreCourseManager() {
		return originalScoreCourseManager;
	}

	public void setOriginalScoreCourseManager(OriginalScoreCourseManager originalScoreCourseManager) {
		this.originalScoreCourseManager = originalScoreCourseManager;
	}
	public VcodeManager getVcodeManager() {
		return vcodeManager;
	}
	public void setVcodeManager(VcodeManager vcodeManager) {
		this.vcodeManager = vcodeManager;
	}
	public VyearCollegeManager getVyearCollegeManager() {
		return vyearCollegeManager;
	}
	public void setVyearCollegeManager(VyearCollegeManager vyearCollegeManager) {
		this.vyearCollegeManager = vyearCollegeManager;
	}
	public GradeMajorManager getGradeMajorManager() {
		return gradeMajorManager;
	}
	public void setGradeMajorManager(GradeMajorManager gradeMajorManager) {
		this.gradeMajorManager = gradeMajorManager;
	}
	public StoreProcedureManager getStoreProcedureManager() {
		return storeProcedureManager;
	}
	public void setStoreProcedureManager(StoreProcedureManager storeProcedureManager) {
		this.storeProcedureManager = storeProcedureManager;
	}

	public ScoreManager getScoreManager() {
		return scoreManager;
	}

	public void setScoreManager(ScoreManager scoreManager) {
		this.scoreManager = scoreManager;
	}

	public BasicDataManager getBasicDataManager() {
		return basicDataManager;
	}

	public void setBasicDataManager(BasicDataManager basicDataManager) {
		this.basicDataManager = basicDataManager;
	}

	public StudentManager getStudentManager() {
		return studentManager;
	}

	public void setStudentManager(StudentManager studentManager) {
		this.studentManager = studentManager;
	}
}
